﻿using Microsoft.AspNetCore.Mvc;
using WoodAdmin.Models;
using WoodAdmin.Services;
using SqlSugar;
using System.Linq;
using X.PagedList;

namespace WoodAdmin.Controllers
{
    public class GlobalSqlController : BaseController
    {
        private readonly GlobalSqlService _service;

        public GlobalSqlController(GlobalSqlService service)
        {
            _service = service;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(SysGlobalSql model,int page =1)
        {
            ViewBag.SearchModel = model;
            var list = _service.Queryable();
            if (!string.IsNullOrEmpty(model.SQLKey))
            {
                list = list.Where(a => SqlFunc.Contains(a.SQLKey, model.SQLKey)).ToList();
            }
            var pageList = list.ToPagedList(page, 15);
            return View(pageList);
        }
        #endregion

        #region 编辑
        /// <summary>
        /// 编辑/添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult AddEdit(int id)
        {
            SysGlobalSql model = _service.FindEntity(id);
            if (model==null)
            {
                model = new SysGlobalSql();
            }
            return View(model);
        }

        /// <summary>
        /// 编辑/添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddEdit(SysGlobalSql model)
        {
            bool rs = false;
            if (model.ID>0)
            {
                if (_service.Update(model))
                {
                    rs = true;
                }
            }
            else
            {
                if (_service.Insert(model))
                {
                    rs = true;
                }
            }
            if (rs)
            {
                return JsonSuccess("保存成功！");
            }
           return JsonError("保存失败");
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Delete(int id)
        {
            if (_service.Delete(id))
            {
                return JsonSuccess("删除成功！");
            }
            return JsonError("删除失败");
        }
        #endregion
    }
}